package com.huiqiao;

import com.huiqiao.mapper.UserMapper;
import com.huiqiao.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyBatisDemo {

    public static void main(String[] args) throws IOException {

        selectAllMethod1();

        selectAllMethod2();

    }

    /**
     * Mybatis最小化使用
     */
    static void selectAllMethod1() throws IOException {
        // 1.从 XML 中构建 SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        // 2.从 SqlSessionFactory 中获取 SqlSession
        // 使用try-with-resources语法，省略 sqlSession.close();
        try (SqlSession session = sqlSessionFactory.openSession()) {

            // 3. 执行sql
            List<User> userList = session.selectList("test.selectAll");
            System.out.println(userList);
        }
    }

    /**
     * 基于UserMapper代理对象发起
     */
    static void selectAllMethod2() throws IOException {
        // 1.从 XML 中构建 SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        // 2.从 SqlSessionFactory 中获取 SqlSession
        // 使用try-with-resources语法，省略 sqlSession.close();
        try (SqlSession session = sqlSessionFactory.openSession()) {
            // 3. 获取UserMapper代理对象
            UserMapper userMapper = session.getMapper(UserMapper.class);

            // 4. 执行sql
            List<User> userList = userMapper.selectAll();
            System.out.println(userList);
        }
    }
}
